import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/note_provider.dart';
import '../../widgets/platform/adaptive_button.dart';
import 'package:go_router/go_router.dart';
import '../../../domain/entities/note.dart';
import '../../../domain/entities/note_request.dart'; // 添加请求实体导入

/// 笔记编辑页面
class NoteEditPage extends ConsumerStatefulWidget {
  final int? noteId; // null表示创建新笔记，非null表示编辑现有笔记

  const NoteEditPage({super.key, this.noteId});

  @override
  ConsumerState<NoteEditPage> createState() => _NoteEditPageState();
}

class _NoteEditPageState extends ConsumerState<NoteEditPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _titleController;
  late TextEditingController _contentController;
  late TextEditingController _tagsController;
  NoteType _selectedType = NoteType.general;
  bool _isPublic = false;

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController();
    _contentController = TextEditingController();
    _tagsController = TextEditingController();

    // 如果是编辑模式，加载笔记详情
    if (widget.noteId != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ref.read(noteStateProvider.notifier).loadNote(widget.noteId!);
      });
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _tagsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentNote = ref.watch(currentNoteProvider);

    // 如果是编辑模式且笔记已加载，填充表单
    if (widget.noteId != null && currentNote != null) {
      _titleController.text = currentNote.title;
      _contentController.text = currentNote.content;
      _tagsController.text = currentNote.tags.join(', ');
      _selectedType = currentNote.noteType;
      _isPublic = currentNote.isPublic;
    }

    return Scaffold(
      appBar: AppBar(
        title: SelectableText(widget.noteId == null ? '创建笔记' : '编辑笔记'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveNote,
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              TextFormField(
                controller: _titleController,
                decoration: const InputDecoration(
                  labelText: '标题 *',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入标题';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 类型选择
              const SelectableText(
                '类型',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8.0,
                children: NoteType.values.map((type) {
                  return ChoiceChip(
                    label: SelectableText(type.description),
                    selected: _selectedType == type,
                    onSelected: (selected) {
                      setState(() {
                        _selectedType = type;
                      });
                    },
                  );
                }).toList(),
              ),
              const SizedBox(height: 16),

              // 标签
              TextFormField(
                controller: _tagsController,
                decoration: const InputDecoration(
                  labelText: '标签 (用逗号分隔)',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),

              // 公开状态
              Row(
                children: [
                  const SelectableText('公开笔记'),
                  const SizedBox(width: 16),
                  Switch(
                    value: _isPublic,
                    onChanged: (value) {
                      setState(() {
                        _isPublic = value;
                      });
                    },
                  ),
                ],
              ),
              const SizedBox(height: 16),

              // 内容
              const SelectableText(
                '内容 *',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Container(
                height: 300,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(4.0),
                ),
                child: TextFormField(
                  controller: _contentController,
                  expands: true,
                  maxLines: null,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.all(16.0),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入内容';
                    }
                    return null;
                  },
                ),
              ),
              const SizedBox(height: 24),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: AdaptiveButton(
                      onPressed: () {
                        context.pop();
                      },
                      child: const SelectableText('取消'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: AdaptiveButton(
                      onPressed: _saveNote,
                      child:
                          SelectableText(widget.noteId == null ? '创建' : '保存'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 保存笔记
  void _saveNote() {
    if (_formKey.currentState!.validate()) {
      final tags = _tagsController.text
          .split(',')
          .map((tag) => tag.trim())
          .where((tag) => tag.isNotEmpty)
          .toList();

      if (widget.noteId == null) {
        // 创建新笔记
        final request = NoteCreateRequest(
          title: _titleController.text,
          content: _contentController.text,
          noteType: _selectedType,
          tags: tags,
          authorId: 1, // 实际应用中应该从当前用户获取
          isPublic: _isPublic,
        );

        ref.read(noteStateProvider.notifier).createNote(request).then((_) {
          // 创建成功后返回上一页
          context.pop();
        });
      } else {
        // 更新现有笔记
        final request = NoteUpdateRequest(
          title:
              _titleController.text.isNotEmpty ? _titleController.text : null,
          content: _contentController.text.isNotEmpty
              ? _contentController.text
              : null,
          noteType: _selectedType,
          tags: tags.isNotEmpty ? tags : null,
          isPublic: _isPublic,
        );

        ref
            .read(noteStateProvider.notifier)
            .updateNote(widget.noteId!, request)
            .then((_) {
          // 更新成功后返回上一页
          context.pop();
        });
      }
    }
  }
}
